package com.gzq.service.serviceImpl;

import com.gzq.entity.Article;
import com.gzq.repository.ArticleRepository;
import com.gzq.service.ArticleService;
import com.gzq.utils.MyUtil;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: duzi55
 * @date: 2019-06-03 16:15
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    ArticleRepository articleRepository;
    @Override
    public Page<Article> findAll(int page) {
        Pageable pageable = new PageRequest(page,5, Sort.Direction.ASC,"id");

        List<Article> list=new ArrayList<Article>();
        for (Article art:articleRepository.findAll(pageable)) {
          String text =  art.getText();
           text = MyUtil.delHTMLTag(text);
           text=text.length()>50?text.substring(0,50):text;
           text=text+"...";
           art.setText(text);
           list.add(art);
        }
        Page page1=new PageImpl(list,pageable,articleRepository.findAll(pageable).getTotalElements());
        return page1 ;
    }

    @Override
    public boolean savaNew(Article article) {
        boolean flag = false;
        if(articleRepository.save(article)!= null){
            flag = true;
        }
        return flag;
    }

    @Override
    public Article findById(long id) {
        return articleRepository.findById(id);
    }

    @Override
    @Transactional
    public boolean deletById(long id) {

        return articleRepository.deleteById(id)>0;
    }

    @Override
    public boolean updateNews(Article article) {

        return  articleRepository.save(article)==null;
    }

    @Override
    public List<Article> findBytitleLike(String title) {
        List<Article> list = new ArrayList<Article>();
        for (Article art : articleRepository.findByTitleLike("%" + title + "%")) {
            String text = art.getText();
            text = MyUtil.delHTMLTag(text);
            text = text.length() > 50 ? text.substring(0, 50) : text;
            text = text + "...";
            art.setText(text);
            list.add(art);
        }
        return list;
    }
}
